#include "mainwindow.h"
#include "ui_mainwindow.h"


using namespace cv;
using namespace std;


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mdiArea = ui->mdiArea;

    cmdStartHomography = ui->cmdStartHomography;
    cmdGoPTZ = ui->cmdGoPoint;

    cmdStampa = ui->cmdStampa;
    cmdGoHome = ui->cmdGoHome;
    cmdSaveFrame = ui->cmdSaveFrame;
    cmdGoABS = ui->cdmGoABS;
    X = ui->editX;
    Y = ui->EditY;
    Z = ui->EditZ;
    _registra = false;
    x=0;
    y=0;
    z=0;


    camVideo = new CSourceManager("TEST",mdiArea);
    camVideo->Init(this);


    PTCal = new PTCalibration("camera-fac-fac.ing.unimo.it",80,"root","cvpr",camVideo);

    //SOLO SE VOGLIO REGISTRARE DA STACCARE NORMALEMENTE
    _registratore = new CVideoOutput_JPG("imagesPT/", "Detector", 50);


    _setDetector = false;

    //Connetti ogni frame che arriva al disegnatore della vista



    //Movimento relativo
    connect(cmdGoPTZ,SIGNAL(clicked()),this,SLOT(sl_movePoint()));

    //Gestisce il detector e fa partire l'omografia
    connect(camVideo,SIGNAL(onNewFrame(CImageRGB*)),this,SLOT(sl_drawDetercorView(CImageRGB*)));

    //Pulsante per cominciare la procedura per la ricerca dell'omografia
    connect(cmdStartHomography,SIGNAL(clicked()),this,SLOT(sl_onDetecor()));

    connect(cmdStampa,SIGNAL(clicked()),this,SLOT(sl_stamp()));

    connect(cmdGoHome,SIGNAL(clicked()),this,SLOT(sl_moveHome()));

    connect(cmdSaveFrame,SIGNAL(clicked()),this,SLOT(sl_SaveFrame()));

    connect(cmdGoABS,SIGNAL(clicked()),this,SLOT(sl_movePointABS()));


}


void MainWindow::capturePosition()
{
    x = X->text().toInt();
    y = Y->text().toInt();
    z = Z->text().toInt();
}

void MainWindow::captureMoved()
{
    Pan = X->text().toFloat();
    Tilt = Y->text().toFloat();
    Zoom = Z->text().toInt();
}

void MainWindow::sl_movePoint()
{
    captureMoved();
    PTCal->movePoint(Pan,Tilt,Zoom);
}

void MainWindow::sl_movePointABS()
{
    captureMoved();
    PTCal->movePointABS(Pan,Tilt,Zoom);
}

void MainWindow::sl_SaveFrame()
{
    _registra = true;
}

void MainWindow::sl_moveHome()
{
    PTCal->GoPreset(CStr("marco_crowd_3"));

}



void MainWindow::sl_onDetecor()
{
    _setDetector = true;
}

void MainWindow::sl_drawDetercorView(CImageRGB *frame)
{
    if(_setDetector)
    {

        PTCal->startHomographyCreation(frame, CStr("marco_crowd_3"));
        //imshow("Detecort", CImageRGB2IplImage(frame));
        _setDetector = false;

    }

    if(_registra)
    {
        _registratore->AppendFrame(frame);
        _registra = false;
    }

}

void MainWindow::sl_stamp()
{

    capturePosition();
    PTCal->stampaProva(x,y,z);

}


MainWindow::~MainWindow()
{
    delete ui;
}
